import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Not } from 'typeorm';
import * as bcrypt from "bcryptjs";

import { User } from '../entity/user.entity';
import { decryptAes } from '../utils';

@Provide()
export class UserService {
    @InjectEntityModel(User)
    userModel: Repository<User>;

    /**
     * 创建用户
     */
    async create(user: Partial<User>): Promise<User> {
        // 检查用户名是否存在
        const existUser = await this.userModel.findOne({
            where: { username: user.username }
        });
        if (existUser) {
            throw new Error('用户名已存在');
        }

        const pw = bcrypt.hashSync(decryptAes(user.password), 10)
        user.password = pw
        const newUser = this.userModel.create(user);
        return await this.userModel.save(newUser);
    }

    /**
     * 更新用户
     */
    async update(id: number, user: Partial<User>): Promise<boolean> {
        if (user.username) {
            const existUser = await this.userModel.findOne({
                where: { username: user.username, id: Not(id) }
            });
            if (existUser) {
                throw new Error('用户名已存在');
            }
        }

        const result = await this.userModel.update(id, user);
        return result.affected > 0;
    }

    /**
     * 删除用户（软删除）
     */
    async delete(id: number): Promise<boolean> {
        const result = await this.userModel.update(id, {
            delFlag: 1,
            updateTime: new Date()
        });
        return result.affected > 0;
    }

    /**
     * 获取用户信息
     */
    async getInfo(id: number): Promise<User> {
        return await this.userModel.findOne({
            where: { id, delFlag: 0 }
        });
    }

    /**
     * 获取用户列表
     */
    async getList(params: {
        page?: number;
        pageSize?: number;
        username?: string;
        status?: number;
        deptId?: number;
    }): Promise<[User[], number]> {
        const { page = 1, pageSize = 10, username, status, deptId } = params;

        const queryBuilder = this.userModel.createQueryBuilder('user')
            .where('user.delFlag = :delFlag', { delFlag: 0 });

        if (username) {
            queryBuilder.andWhere('user.username LIKE :username', {
                username: `%${username}%`
            });
        }

        if (status !== undefined) {
            queryBuilder.andWhere('user.status = :status', { status });
        }

        if (deptId) {
            queryBuilder.andWhere('user.deptId = :deptId', { deptId });
        }

        return await queryBuilder
            .skip((page - 1) * pageSize)
            .take(pageSize)
            .orderBy('user.createTime', 'DESC')
            .getManyAndCount();
    }
} 